// pages/category/category.js
const app = getApp();
Page({
  data: {
    tabs: [],
    activeTab: '',
    activeTabIndex: 0,

    // 电控品牌
    brandList: [],
    selectedBrandIndex: 0,
    currentBrandTypes: [],
    selectedBrandTypeIndex: 0,
    currentBrandItems: [], // 从接口获取的产品列表

    // 机器类型
    machineList: [],
    selectedMachineIndex: 0,
    currentMachineTypes: [],
    selectedMachineTypeIndex: 0,
    currentMachineItems: [], // 从接口获取的产品列表

    // 品牌型号
    modelList: [],
    selectedModelBrandIndex: 0,
    currentModelTypes: [],
    selectedModelTypeIndex: 0,
    currentModelItems: [], // 从接口获取的产品列表

    categoryId: '',
    categoryTree: null, // 存储完整的分类树
  },

  onLoad(options) {
    this.setData({
      categoryId: options.categoryId || ''
    });
    
    // 设置页面标题
    if (options.categoryName) {
      wx.setNavigationBarTitle({
        title: options.categoryName
      });
    }
    
    this.getCategoryList();
  },
  loadProductList(productCategoryId) {
    if (!productCategoryId) {
      return;
    }
    wx.request({
      url: `${app.globalData.baseUrl}/product/listWithMedia?productCategoryId=${productCategoryId}&productType=-1`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200 && res.data.rows) {
          // 转换数据格式，适配右侧商品列表
          const products = (res.data.rows || []).map(item => ({
            categoryId: item.productId || item.categoryId || item.id,
            name: item.productName || item.name || item.title,
            image: item.productPicture || item.image || item.mediaUrl
          }));
          
          // 根据当前tab更新对应的产品列表
          const { activeTab } = this.data;
          if (activeTab === 'brand') {
            this.setData({ currentBrandItems: products });
          } else if (activeTab === 'machine') {
            this.setData({ currentMachineItems: products });
          } else if (activeTab === 'model') {
            this.setData({ currentModelItems: products });
          }
        } else {
          // 如果没有数据，清空列表
          const { activeTab } = this.data;
          if (activeTab === 'brand') {
            this.setData({ currentBrandItems: [] });
          } else if (activeTab === 'machine') {
            this.setData({ currentMachineItems: [] });
          } else if (activeTab === 'model') {
            this.setData({ currentModelItems: [] });
          }
        }
      },
      fail: (err) => {
        console.error('获取产品列表失败:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
        // 失败时清空列表
        const { activeTab } = this.data;
        if (activeTab === 'brand') {
          this.setData({ currentBrandItems: [] });
        } else if (activeTab === 'machine') {
          this.setData({ currentMachineItems: [] });
        } else if (activeTab === 'model') {
          this.setData({ currentModelItems: [] });
        }
      }
    });
  },
  onBrandItemClick(e) {
    const categoryId = e.currentTarget.dataset.id;
    if (categoryId) {
      wx.navigateTo({
        url: `/pages/details/details?productId=${categoryId}`
      });
    }
  },

  onMachineItemClick(e) {
    const categoryId = e.currentTarget.dataset.id;
    if (categoryId) {
      wx.navigateTo({
        url: `/pages/details/details?productId=${categoryId}`
      });
    }
  },

  onModelItemClick(e) {
    const categoryId = e.currentTarget.dataset.id;
    if (categoryId) {
      wx.navigateTo({
        url: `/pages/details/details?productId=${categoryId}`
      });
    }
  },

  getCategoryList() {
    wx.request({
      url: `${app.globalData.baseUrl}/category/tree?categoryId=${this.data.categoryId}`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
          const rootCategory = res.data.data[0];
          this.setData({
            categoryTree: rootCategory
          });
          this.parseCategoryData(rootCategory);
        } else {
          wx.showToast({
            title: '暂无数据',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取分类树失败:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    });
  },

  parseCategoryData(rootCategory) {
    if (!rootCategory || !rootCategory.children || rootCategory.children.length === 0) {
      return;
    }

    const firstLevelCategories = rootCategory.children;
    const tabs = [];
    let brandCategory = null;
    let machineCategory = null;
    let modelCategory = null;

    // 解析三个一级分类
    firstLevelCategories.forEach(category => {
      const categoryName = category.categoryName;
      if (categoryName === '电控品牌') {
        brandCategory = category;
        tabs.push({ key: 'brand', label: '电控品牌', categoryId: category.categoryId });
      } else if (categoryName === '机器类型') {
        machineCategory = category;
        tabs.push({ key: 'machine', label: '机器类型', categoryId: category.categoryId });
      } else if (categoryName === '品牌型号') {
        modelCategory = category;
        tabs.push({ key: 'model', label: '品牌型号', categoryId: category.categoryId });
      }
    });

    // 设置tabs和默认选中第一个
    this.setData({
      tabs: tabs,
      activeTab: tabs.length > 0 ? tabs[0].key : '',
      activeTabIndex: 0
    });

    // 解析电控品牌数据
    if (brandCategory && brandCategory.children) {
      const brandList = brandCategory.children.map(secondLevel => ({
        categoryId: secondLevel.categoryId,
        name: secondLevel.categoryName,
        types: secondLevel.children ? secondLevel.children.map(thirdLevel => ({
          categoryId: thirdLevel.categoryId,
          name: thirdLevel.categoryName,
          items: thirdLevel.children ? thirdLevel.children.map(item => ({
            categoryId: item.categoryId,
            name: item.categoryName
          })) : []
        })) : []
      }));
      this.setData({ brandList }, () => {
        this.updateBrandColumns();
      });
    }

    // 解析机器类型数据
    if (machineCategory && machineCategory.children) {
      const machineList = machineCategory.children.map(secondLevel => ({
        categoryId: secondLevel.categoryId,
        name: secondLevel.categoryName,
        types: secondLevel.children ? secondLevel.children.map(thirdLevel => ({
          categoryId: thirdLevel.categoryId,
          name: thirdLevel.categoryName,
          items: thirdLevel.children ? thirdLevel.children.map(item => ({
            categoryId: item.categoryId,
            name: item.categoryName
          })) : []
        })) : []
      }));
      this.setData({ machineList }, () => {
        this.updateMachineColumns();
      });
    }

    // 解析品牌型号数据
    if (modelCategory && modelCategory.children) {
      const modelList = modelCategory.children.map(secondLevel => ({
        categoryId: secondLevel.categoryId,
        brand: secondLevel.categoryName,
        types: secondLevel.children ? secondLevel.children.map(thirdLevel => ({
          categoryId: thirdLevel.categoryId,
          name: thirdLevel.categoryName,
          items: thirdLevel.children ? thirdLevel.children.map(item => ({
            categoryId: item.categoryId,
            name: item.categoryName
          })) : []
        })) : []
      }));
      this.setData({ modelList }, () => {
        this.updateModelColumns();
      });
    }
  },
  onTabChange(e) {
    const { key } = e.currentTarget.dataset;
    const tabIndex = e.currentTarget.dataset.index;
    if (!key || key === this.data.activeTab) return;
    this.setData({ 
      activeTab: key,
      activeTabIndex: tabIndex || 0
    }, () => {
      if (key === 'brand') {
        this.updateBrandColumns();
      } else if (key === 'machine') {
        this.updateMachineColumns();
      } else if (key === 'model') {
        this.updateModelColumns();
      }
    });
  },

  onBrandSelect(e) {
    const index = Number(e.currentTarget.dataset.index);
    if (Number.isNaN(index) || index === this.data.selectedBrandIndex) return;
    this.setData(
      {
        selectedBrandIndex: index,
        selectedBrandTypeIndex: 0,
      },
      () => {
        this.updateBrandColumns();
      },
    );
  },

  onBrandTypeSelect(e) {
    const index = Number(e.currentTarget.dataset.index);
    if (Number.isNaN(index) || index === this.data.selectedBrandTypeIndex) return;
    const selectedType = this.data.currentBrandTypes[index];
    this.setData({ selectedBrandTypeIndex: index }, () => {
      // 调用接口获取产品列表
      if (selectedType && selectedType.categoryId) {
        this.loadProductList(selectedType.categoryId, 'brand');
      } else {
        this.setData({ currentBrandItems: [] });
      }
    });
  },

  onMachineSelect(e) {
    const index = Number(e.currentTarget.dataset.index);
    if (Number.isNaN(index) || index === this.data.selectedMachineIndex) return;
    this.setData(
      {
        selectedMachineIndex: index,
        selectedMachineTypeIndex: 0,
      },
      () => {
        this.updateMachineColumns();
      },
    );
  },

  onMachineTypeSelect(e) {
    const index = Number(e.currentTarget.dataset.index);
    if (Number.isNaN(index) || index === this.data.selectedMachineTypeIndex) return;
    const selectedType = this.data.currentMachineTypes[index];
    this.setData({ selectedMachineTypeIndex: index }, () => {
      // 调用接口获取产品列表
      if (selectedType && selectedType.categoryId) {
        this.loadProductList(selectedType.categoryId, 'machine');
      } else {
        this.setData({ currentMachineItems: [] });
      }
    });
  },

  onModelBrandSelect(e) {
    const index = Number(e.currentTarget.dataset.index);
    if (Number.isNaN(index) || index === this.data.selectedModelBrandIndex) return;
    this.setData(
      {
        selectedModelBrandIndex: index,
        selectedModelTypeIndex: 0,
      },
      () => {
        this.updateModelColumns();
      },
    );
  },

  onModelTypeSelect(e) {
    const index = Number(e.currentTarget.dataset.index);
    if (Number.isNaN(index) || index === this.data.selectedModelTypeIndex) return;
    const selectedType = this.data.currentModelTypes[index];
    this.setData({ selectedModelTypeIndex: index }, () => {
      // 调用接口获取产品列表
      if (selectedType && selectedType.categoryId) {
        this.loadProductList(selectedType.categoryId, 'model');
      } else {
        this.setData({ currentModelItems: [] });
      }
    });
  },


  updateModelColumns() {
    const { modelList, selectedModelBrandIndex } = this.data;
    const brand = modelList[selectedModelBrandIndex] || {};
    const types = brand.types || [];
    const selectedTypeIndex = Math.min(this.data.selectedModelTypeIndex, Math.max(types.length - 1, 0));
    const selectedType = types[selectedTypeIndex];
    
    this.setData({
      currentModelTypes: types,
      selectedModelTypeIndex: selectedTypeIndex,
      currentModelItems: [], // 清空，等待接口加载
    });
    
    // 如果有选中的类型，自动加载产品列表
    if (selectedType && selectedType.categoryId) {
      this.loadProductList(selectedType.categoryId, 'model');
    }
  },

  updateBrandColumns() {
    const { brandList, selectedBrandIndex } = this.data;
    const brand = brandList[selectedBrandIndex] || {};
    const types = brand.types || [];
    const selectedTypeIndex = Math.min(this.data.selectedBrandTypeIndex, Math.max(types.length - 1, 0));
    const selectedType = types[selectedTypeIndex];
    
    this.setData({
      currentBrandTypes: types,
      selectedBrandTypeIndex: selectedTypeIndex,
      currentBrandItems: [], // 清空，等待接口加载
    });
    
    // 如果有选中的类型，自动加载产品列表
    if (selectedType && selectedType.categoryId) {
      this.loadProductList(selectedType.categoryId, 'brand');
    }
  },

  updateMachineColumns() {
    const { machineList, selectedMachineIndex } = this.data;
    const machine = machineList[selectedMachineIndex] || {};
    const types = machine.types || [];
    const selectedTypeIndex = Math.min(this.data.selectedMachineTypeIndex, Math.max(types.length - 1, 0));
    const selectedType = types[selectedTypeIndex];
    
    this.setData({
      currentMachineTypes: types,
      selectedMachineTypeIndex: selectedTypeIndex,
      currentMachineItems: [], // 清空，等待接口加载
    });
    
    // 如果有选中的类型，自动加载产品列表
    if (selectedType && selectedType.categoryId) {
      this.loadProductList(selectedType.categoryId, 'machine');
    }
  },

  loadProductList(productCategoryId, tabType) {
    wx.request({
      url: `${app.globalData.baseUrl}/product/listWithMedia?productCategoryId=${productCategoryId}&productType=-1`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200 && res.data.rows) {
          // 转换数据格式，适配右侧商品列表
          const products = (res.data.rows || []).map(item => ({
            categoryId: item.productId || item.categoryId || item.id,
            name: item.productName || item.name || item.title,
            image: item.productPicture || item.image || item.mediaUrl || ''
          }));
          
          // 根据tab类型赋值给对应的items
          const dataKey = tabType === 'brand' ? 'currentBrandItems' : 
                         tabType === 'machine' ? 'currentMachineItems' : 
                         'currentModelItems';
          
          this.setData({
            [dataKey]: products
          });
        } else {
          // 如果没有数据，清空对应的items
          const dataKey = tabType === 'brand' ? 'currentBrandItems' : 
                         tabType === 'machine' ? 'currentMachineItems' : 
                         'currentModelItems';
          this.setData({
            [dataKey]: []
          });
        }
      },
      fail: (err) => {
        console.error('获取产品列表失败:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
        // 失败时也清空对应的items
        const dataKey = tabType === 'brand' ? 'currentBrandItems' : 
                       tabType === 'machine' ? 'currentMachineItems' : 
                       'currentModelItems';
        this.setData({
          [dataKey]: []
        });
      }
    });
  },

});